import { storage } from '@doctorwork/saga';
import { isHybrid } from '../utils/h5/hybrid';

const report = process.env.TARO_ENV == 'weapp' ? wx.reportAnalytics : () => {};

export default {
    namespace: 'analyse',
    state: { lastTime: '' },
    reducers: {},
    effects: {
        /**
         * 添加分析上报
         * @param {*} param0 {name,data}={上报名称,上报数据}
         * @param {*} param1
         */
        *set({ payload }, { put }) {
            // 1. 获取上一次上报的时间
            // const lastTime = select(state => state.analyse.lastTime);
            let name = payload.name; //上报名称
            let data = payload.data; //上报数据

            let placeId = isHybrid
                ? ''
                : yield put.resolve({ type: 'getSource' }); //从缓存里面取
            placeId = placeId || '0000'; //没有就直接使用默认值
            const anotherData = { ...data, place: placeId };
            console.log('埋点统计  name:', name, ' data:', anotherData);
            report(name, anotherData);
        },
        *getSource(action, { put }) {
            const trace = yield put.resolve({
                type: '$storage/get',
                payload: 'x-trace'
            }); //从缓存里面取
            if (!trace) return '';
            let header = {};
            trace.split(',').forEach(elm => {
                const [key, value] = elm.split(':');
                header[key] = value;
            });
            return header.source || '';
        }
    }
};

const actions = ['goodsOrder/createOrder', '@init', 'festival/checkRunAuth'];
const match = action => {
    if (~actions.indexOf(action.type)) {
    }
};

// 打点插件
export const AnalyseMiddleware = ({ dispatch }) => next => action => {
    let matched = match(action);
    if (matched) {
        dispatch(matched);
    }

    next(action);
};
